package com.yizhubao.app.activitys;


import android.content.DialogInterface;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.wei.android.lib.fingerprintidentify.FingerprintIdentify;
import com.wei.android.lib.fingerprintidentify.base.BaseFingerprint;
import com.yizhubao.app.MainActivity;
import com.yizhubao.app.R;
import com.yizhubao.app.app.YZBApp;
import com.yizhubao.app.base.BaseActivity;
import com.yizhubao.app.base.BaseResultBean;
import com.yizhubao.app.beans.WXLoginBean;
import com.yizhubao.app.customviews.IdentifyDialog;
import com.yizhubao.app.customviews.LoginLableDialog;
import com.yizhubao.app.events.LoginEvent;
import com.yizhubao.app.events.WXLoginEvent;
import com.yizhubao.app.models.WXLoginModel;
import com.yizhubao.app.presenters.WXLoginPresenter;
import com.yizhubao.app.utils.Constants;
import com.yizhubao.app.utils.Utils;
import com.yizhubao.app.utils.net.BaseObserver;
import com.yizhubao.app.views.WXLoginView;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import h.framework.pacy.utils.LogUtil;
import h.framework.pacy.utils.PreferencesUtil;
import h.framework.pacy.utils.ToastUtil;

/**
 * 创建人: PACY
 * 创建时间: 6/6/21 10:25 AM
 * 邮箱: pengwwe457621023@qq.com
 * 类描述: 启动页
 */
public class WelcomeActivity extends BaseActivity implements WXLoginView {


    FingerprintIdentify mFingerprintIdentify;
    IdentifyDialog identifyDialog;
    LoginLableDialog loginLableDialog;
    WXLoginModel loginModel;
    int status=1;

    @BindView(R.id.start_btn)
    TextView start_btn;

    private int errorNum=0;

    WXLoginPresenter presenter;

    boolean isLogin=true;
    @Override
    protected int setContentLayout() {
        return R.layout.activity_welcome;
    }

    @Override
    protected void initView() {
        YZBApp.getInstance().addWelcomeActivity(this);
        EventBus.getDefault().register(this);
        identifyDialog=new IdentifyDialog(WelcomeActivity.this);
        loginLableDialog=new LoginLableDialog(WelcomeActivity.this);
        identifyDialog.setOnDismissListener(dialog -> {
            if(mFingerprintIdentify!=null){
                LogUtil.i("弹窗dismiss");
                mFingerprintIdentify.cancelIdentify();
            }
        });
    }

    @Override
    protected void initData() {
        presenter=new WXLoginPresenter();
        presenter.attachView(this);
        loginModel=new WXLoginModel();
        if(Utils.isLogin()){
            sendUserRequest();
            if(Utils.isPay()){
                start_btn.setText("进入使用");
            }else{
                start_btn.setText("先看介绍 , 再去使用");
            }
        }else{
            start_btn.setText("先看介绍 , 再去使用");
        }
    }


    /**
     * 获取用户信息
     */
    private void sendUserRequest(){
        showLoading();
        loginModel.getUser(new BaseObserver<WXLoginBean>() {
            @Override
            public void onSuccess(BaseResultBean<WXLoginBean> t) {
                    LogUtil.i("获取用户信息"+t.getData().toString());
                    Utils.saveUser(t.getData());
                    status=t.getData().getStatus();
                        isLogin=false;

            }
            @Override
            public void onError(String errMessage) {
                LogUtil.i("获取用户信息"+errMessage);
            }

            @Override
            public void onLogin() {
                super.onLogin();
                isLogin=true;
            }

            @Override
            public void onComplete() {
                super.onComplete();
                dismissDialog();
            }
        },lifecycleSubject);
    }

    @OnClick(value = {R.id.start_btn,R.id.tiaokuan})
    public void click(View v){
        if(v.getId()==R.id.start_btn){
            if(status==1){
                if(Utils.isLogin()){
                    if(isLogin){
                        loginLableDialog.show();
                        loginForWX();
                    }else{
                        if(Utils.isPay()){
                            identifyDialog.show();
                            startIdentify();
                        }else{
                            startActivity(WelcomeActivity.this,NewsActivity.class);
                        }
                    }
                }else{
                    startActivity(WelcomeActivity.this,NewsActivity.class);
                }

            }else{
                Bundle bundle=new Bundle();
                bundle.putInt("type",1);
                startActivity(WelcomeActivity.this,ProhibitActivity.class,bundle);
            }

        }else if(v.getId()==R.id.tiaokuan){
            Bundle bundle = new Bundle();
            bundle.putString("title", "条款");
            bundle.putString("url", Constants.QUESTION);
            startActivity(WelcomeActivity.this, WebActivity.class, bundle);
        }
    }

    /**
     * 检测指纹识别
     */
    private void startIdentify(){
        if(mFingerprintIdentify==null){
            mFingerprintIdentify = new FingerprintIdentify(this);       // 构造对象
            mFingerprintIdentify.setSupportAndroidL(true);              // 支持安卓L及以下系统
//        mFingerprintIdentify.setExceptionListener(listener);        // 错误回调（错误仅供开发使用）
            mFingerprintIdentify.init();
        }

        if( !mFingerprintIdentify.isFingerprintEnable()){
            Bundle bundle=new Bundle();
            bundle.putInt("jumpType",1);
            startActivity(WelcomeActivity.this,AuthActivity.class,bundle);
           return;
        }
        // 指纹硬件是否可用
        if( !mFingerprintIdentify.isHardwareEnable()){
            Bundle bundle=new Bundle();
            bundle.putInt("jumpType",1);
            startActivity(WelcomeActivity.this,AuthActivity.class,bundle);
            return;
        }
        // 指纹硬件可用并已经录入指纹
        if( !mFingerprintIdentify.isRegisteredFingerprint()){
            Bundle bundle=new Bundle();
            bundle.putInt("jumpType",1);
            startActivity(WelcomeActivity.this,AuthActivity.class,bundle);
            return;
        }

        mFingerprintIdentify.startIdentify(6000, new BaseFingerprint.IdentifyListener() {
            @Override
            public void onSucceed() {
                LogUtil.i("指纹验证成功");
                identifyDialog.setTitle("指纹验证成功");
                startActivity(WelcomeActivity.this, MainActivity.class);
//                startActivity(WelcomeActivity.this,NewsActivity.class);
               finish();
            }

            @Override
            public void onNotMatch(int availableTimes) {
//                ToastUtil.showShort("指纹识别失败，请重试");
                LogUtil.i("指纹识别失败，请重试");
                identifyDialog.setTitle("指纹识别失败，请重试");
                errorNum++;
                if(errorNum==3){
                    LogUtil.i("指纹失败三次");
                    Bundle bundle=new Bundle();
                    bundle.putInt("jumpType",1);
                    startActivity(WelcomeActivity.this,AuthActivity.class,bundle);
                }
            }

            @Override
            public void onFailed(boolean isDeviceLocked) {
                LogUtil.e("onFailed");
                Bundle bundle=new Bundle();
                bundle.putInt("jumpType",1);
                startActivity(WelcomeActivity.this,AuthActivity.class,bundle);
            }

            @Override
            public void onStartFailedByDeviceLocked() {
                LogUtil.i("失败次数过多，设备锁定");
//                identifyDialog.setTitle("失败次数过多，设备锁定");
                Bundle bundle=new Bundle();
                bundle.putInt("jumpType",1);
                startActivity(WelcomeActivity.this,AuthActivity.class,bundle);
            }
        });     // 开始验证指纹识别
//        mFingerprintIdentify.cancelIdentify();                      // 关闭指纹识别
//        mFingerprintIdentify.resumeIdentify();                      // 恢复指纹识别并保证错误次数不变

    }
    /**
     * 微信授权
     */
    private void loginForWX(){
        SendAuth.Req req=new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        YZBApp.api.sendReq(req);
    }

    @Subscribe(threadMode = ThreadMode.POSTING,priority = 0)
    public void onWXLoginEvent(WXLoginEvent event){
        loginLableDialog.dismiss();
        LogUtil.i("微信登录welcome=");
        Map<String,Object> map=new HashMap<>();
        map.put("code",event.getCode());
        //微信授权拿到code后发起登录
        showLoading("微信登录");
        presenter.sendWXLoginRequest(map);
    }

    @Override
    public void onWXLoginSuccess(WXLoginBean data) {
        dismissDialog();
        Utils.saveUser(data);
        status=data.getStatus();
        if(status==1){
            sendUserRequest();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }

    /**
     * 处理回退事件
     *
     * @return
     */
    @Override
    public void onBackPressedSupport() {
        YZBApp.getInstance().exit();
    }
}